import Mock from 'mockjs'
import { param2Obj } from '../src/utils'

import project from './project'
import user from './user'
import table from './table'
import task from './task'
// seting
import milepost from './seting/milepost'
import billCategory from './seting/billCategory'
import billTemplate from './seting/billTemplate'
import msg from './seting/msg'
import role from './seting/role'
import tag from './seting/tag'
import taskCategory from './seting/taskCategory'
import taskTemplate from './seting/taskTemplate'
import setingMembers from './seting/members'
//basicData
import members from './basicData/members'
import goods from './basicData/goods'
import bom from './basicData/bom'
import warehouse from './basicData/warehouse'
import bill from './bill'
const mocks = [
  ...project,
  ...user,
  ...task,

  ...milepost,
  ...billCategory,
  ...billTemplate,
  ...msg,
  ...role,
  ...tag,
  ...taskCategory,
  ...taskTemplate,
  ...setingMembers,

  ...members,
  ...goods,
  ...bom,
  ...warehouse,
  
  ...table,
  ...task,
  ...bill,
]

export function mockXHR() {

  Mock.XHR.prototype.proxy_send = Mock.XHR.prototype.send
  Mock.XHR.prototype.send = function () {
    if (this.custom.xhr) {
      this.custom.xhr.withCredentials = this.withCredentials || false

      if (this.responseType) {
        this.custom.xhr.responseType = this.responseType
      }
    }
    this.proxy_send(...arguments)
  }

  function XHR2ExpressReqWrap(respond) {
    return function (options) {
      let result = null
      if (respond instanceof Function) {
        const { body, type, url } = options

        result = respond({
          method: type,
          body: JSON.parse(body),
          query: param2Obj(url)
        })
      } else {
        result = respond
      }
      return Mock.mock(result)
    }
  }

  for (const i of mocks) {
    Mock.mock(new RegExp(i.url), i.type || 'get', XHR2ExpressReqWrap(i.response))
  }
}

// for mock server
const responseFake = (url, type, respond) => {
  return {
    url: new RegExp(`/mock${url}`),
    type: type || 'get',
    response(req, res) {
      res.json(Mock.mock(respond instanceof Function ? respond(req, res) : respond))
    }
  }
}

export default mocks.map(route => {
  return responseFake(route.url, route.type, route.response)
})
// export default mocks
